package quq.missq.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.NetworkImageView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import quq.missq.BaseActivity;
import quq.missq.Constants;
import quq.missq.MLog;
import quq.missq.R;
import quq.missq.adapter.BigShootDetailAdapter;
import quq.missq.adapter.ImageGridViewAdapter;
import quq.missq.beans.Author;
import quq.missq.beans.CommentsBean;
import quq.missq.beans.TopicDetailBean;
import quq.missq.beans.UserBean;
import quq.missq.utils.UserTools;
import quq.missq.utils.VolleyTool;
import quq.missq.views.LoadMoreListView;
import quq.missq.views.NoScrollGridView;
import quq.missq.views.ShareDialog;

/**
 * Created by River on 8/3/15.
 */
public class TopicDetailActivity extends BaseActivity implements VolleyTool.HTTPListener,
        LoadMoreListView.OnLoadMore, View.OnClickListener {

    private LoadMoreListView mListView;
    private LinkedList<CommentsBean.Result> results;
    private BigShootDetailAdapter adapter;
    private TopicDetailBean mDetail = null;

    private int targetType = 1; //  0:大招 1话题

    private ImageView mBack;
    private ImageView mShare;
    private ImageView mComment;
    private ImageView mBLike;
    private ImageView mBUnlike;
    private ImageView mLike;
    private ImageView mUnlike;
    private ImageView mJubao;

    private TextView tvFavors;
    private String atContent = "";
    private int id = 0;
    private boolean desc = true;// 排序，true:时间倒序, false:时间正序
    private int maxResults = 10;
    private int currentPage = 1;
    UserBean.User user = null;
    private TextView mAtUser;
    private ImageView mTypeIcon;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.topic_detail_activity);
        id = getIntent().getExtras().getInt("id");
        user = UserTools.getUser(this);
        MLog.e("打开了话题详情");
        initView();
        initListener();
        initTopicData();
    }

    private void initView() {
        mBack = (ImageView) findViewById(R.id.back);
        mShare = (ImageView) findViewById(R.id.share);
        mComment = (ImageView) findViewById(R.id.comment);
        mLike = (ImageView) findViewById(R.id.like);
        mBLike = (ImageView) findViewById(R.id.like);
        mBUnlike = (ImageView) findViewById(R.id.unlike);
        mListView = (LoadMoreListView) findViewById(R.id.listView);
    }

    private void initCommentData() {
        results = new LinkedList<>();
        adapter = new BigShootDetailAdapter(this, 1, id);
        View view = getHeadView();
        mListView.addHeaderView(view);
        adapter.setData(results);
        mListView.setAdapter(adapter);
        loadCommentNetworkData();
    }

    private View getHeadView() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.topic_detail_head_layout, null);
        ((TextView) view.findViewById(R.id.title)).setText(mDetail.getData().getTitle());
        ((TextView) view.findViewById(R.id.level)).setText("level " + mDetail.getData().getAuthor().getLevel());
        String gender = "男";
        //话题类型图标
        mTypeIcon = (ImageView) view.findViewById(R.id.typeIcon);
        if(mDetail.getData().getCategory().getId() == 3){
            mTypeIcon.setImageResource(R.mipmap.icon_plan);
        }else if(mDetail.getData().getCategory().getId() == 2){
            mTypeIcon.setImageResource(R.mipmap.icon_change);
        }else if(mDetail.getData().getCategory().getId() == 1){
            mTypeIcon.setImageResource(R.mipmap.icon_night);
        }else if(mDetail.getData().getCategory().getId() == 5){
            mTypeIcon.setImageResource(R.mipmap.icon_qa);
        }else if (mDetail.getData().getCategory().getId() == 4){
            mTypeIcon.setImageResource(R.mipmap.icon_show);
        }
        if (mDetail.getData().getAuthor().getGender() == 1) {
            gender = "男";
        } else {
            gender = "女";
        }
        mJubao = (ImageView) view.findViewById(R.id.jubao);
        mJubao.setOnClickListener(this);
        mLike = (ImageView) view.findViewById(R.id.like);
        mUnlike = (ImageView) view.findViewById(R.id.unlikeIcon);
        int liked = mDetail.getData().getFavored();
        if (liked == 0) {
            changeLike(0);
        } else {
            changeLike(1);
        }
        tvFavors = (TextView) view.findViewById(R.id.favors);
        tvFavors.setText(mDetail.getData().getFavors() + "");
        mLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (user != null) {
                    likeOrUnlike(1);
                    int count = Integer.parseInt(tvFavors.getText().toString());
                    tvFavors.setText((count - 1) + "");
                } else {
                    goLogin();
                }
            }
        });
        mUnlike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (user != null) {
                    likeOrUnlike(0);
                    int count = Integer.parseInt(tvFavors.getText().toString());
                    tvFavors.setText((count + 1) + "");
                } else {
                    goLogin();
                }
            }
        });
        ((TextView) view.findViewById(R.id.gender)).setText(gender);
        ((NetworkImageView) view.findViewById(R.id.avtar)).setImageUrl(Constants.IMAGE_HOST + mDetail.getData().getAuthor().getAvatar(), VolleyTool.getImageLoader());
        (view.findViewById(R.id.avtar)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(TopicDetailActivity.this, TaPageActivity.class);
                intent.putExtra("uid", mDetail.getData().getAuthor().getId());
                intent.putExtra("username", mDetail.getData().getAuthor().getNkname());
                TopicDetailActivity.this.startActivity(intent);
            }
        });
        ((TextView) view.findViewById(R.id.name)).setText(mDetail.getData().getAuthor().getNkname());
        ((TextView) view.findViewById(R.id.time)).setText(mDetail.getData().getCreated());
        ((TextView) view.findViewById(R.id.likeCount)).setText(mDetail.getData().getComments() + "");
        ((WebView) view.findViewById(R.id.content)).loadDataWithBaseURL(null, mDetail.getData().getContent(), "text/html", "UTF-8", null);
        ArrayList<Author> atUsers = mDetail.getData().getAtUsers();
        mAtUser = (TextView) view.findViewById(R.id.atuser);
        if(atUsers != null){
            for (Author author:atUsers){
                if ("".equals(atContent)) {
                    atContent = "@" + author.getNkname();
                } else {
                    atContent = atContent + ",@" + author.getNkname();
                }
            }
            //Log.i("TopicDetailActivity",atContent + "=================================================");
            mAtUser.setText(atContent);
        }else{
            mAtUser.setVisibility(View.GONE);
        }

        ImageGridViewAdapter imageAdapter = new ImageGridViewAdapter(this, mDetail.getData().getAttachs());
        NoScrollGridView gridView = (NoScrollGridView) view.findViewById(R.id.gridview);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(TopicDetailActivity.this, ImageViewPagerActivity.class);
                intent.putExtra("position", position);
                ArrayList<String> urls = new ArrayList<>();
                for (int i = 0; i < mDetail.getData().getAttachs().size(); i++) {
                    urls.add(Constants.IMAGE_HOST + mDetail.getData().getAttachs().get(i).getOrigin());
                }
                intent.putExtra("netImageUrls", urls);
                TopicDetailActivity.this.startActivity(intent);
            }
        });
        gridView.setAdapter(imageAdapter);
        return view;
    }

    private void changeLike(int k) {
        if (k == 0) {
            mLike.setVisibility(View.GONE);
            mUnlike.setVisibility(View.VISIBLE);
            mBLike.setVisibility(View.GONE);
            mBUnlike.setVisibility(View.VISIBLE);
        } else {
            mLike.setVisibility(View.VISIBLE);
            mUnlike.setVisibility(View.GONE);
            mBLike.setVisibility(View.VISIBLE);
            mBUnlike.setVisibility(View.GONE);
        }
    }

    private void likeOrUnlike(int viewId) {
        if (user == null) {
            Intent intent1 = new Intent();
            intent1.setClass(this, LoginActivity.class);
            startActivity(intent1);
        } else {
            Map<String, String> params = new HashMap<>();
            params.put("id", id + "");
            params.put("acc_token", user.getAcc_token());
            String url = "";
            if (viewId == 0) {
                changeLike(1);
                url = Constants.FAVOR_TOPIC_URL;
            } else {
                changeLike(0);
                url = Constants.UNFAVOR_TOPIC_URL;
            }
            VolleyTool.get(this, url, params, this, 1, null);
        }
    }

    private void initTopicData() {
        Map<String, String> params = new HashMap<>();
        params.put("id", id + "");
        if (user != null) {
            params.put("acc_token", user.getAcc_token());
        }
        VolleyTool.get(this, Constants.GET_TOPIC_DETAIL_URL, params, this, Constants.GET_TOPIC_DETAIL, TopicDetailBean.class);
    }

    private void loadCommentNetworkData() {
        Map<String, String> params = new HashMap<>();
        params.put("targetId", id + "");
        params.put("pn", currentPage + "");
        params.put("maxResults", maxResults + "");
        params.put("desc", desc + "");
        VolleyTool.get(this, Constants.GET_COMMENTS_LIST_URL, params, this, Constants.GET_COMMENTS_LIST, CommentsBean.class);
    }

    private void initListener() {
        mBack.setOnClickListener(this);
        mShare.setOnClickListener(this);
        mComment.setOnClickListener(this);
        mLike.setOnClickListener(this);
        mListView.setLoadMoreListen(this);
        mBLike.setOnClickListener(this);
        mBUnlike.setOnClickListener(this);
    }

    @Override
    public <T> void onResponse(T t, int requestCode) {
        if (requestCode == Constants.GET_COMMENTS_LIST) {
            CommentsBean bean = (CommentsBean) t;
            if (bean.getCode() >= 0) {
                LinkedList<CommentsBean.Result> beans = bean.getData().getResults();
                if (currentPage == 1) {
                    adapter.getData().clear();
                    adapter.getData().addAll(0, beans);
                    adapter.notifyDataSetChanged();
                } else {
                    if (beans.size() > 0) {
                        adapter.getData().addAll(beans);
                        adapter.notifyDataSetChanged();
                    } else {
                        if (results.size() > 10) {
                            showToast("已加载完所有");
                        }
                    }
                    mListView.onLoadComplete();
                }
            } else {
                showToast(bean.getMessage());
            }
        } else if (requestCode == Constants.GET_TOPIC_DETAIL) {
            mDetail = (TopicDetailBean) t;
            initCommentData();
        }

    }


    @Override
    public void onErrorResponse(VolleyError error, int requestCode) {

    }

    @Override
    public void loadMore() {
        currentPage = currentPage + 1;
        loadCommentNetworkData();
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.comment:
                if (user != null) {
                    intent = new Intent();
                    intent.putExtra("targetType", 1);
                    intent.putExtra("targetId", id);
                    intent.setClass(this, PublishComentActivity.class);
                    goOtherAcitity(intent);
                } else {
                    goLogin();
                }
                break;
            case R.id.share:
                if (user != null) {
                    ShareDialog shareDialog = new ShareDialog(TopicDetailActivity.this);
                    shareDialog.setData_2(mDetail.getData());
                    shareDialog.setType(2);
                    shareDialog.show();
                } else {
                    goLogin();
                }
                break;
            case R.id.like:
                if (user != null) {
                    if (tvFavors != null) {
                        changeLike(0);
                        likeOrUnlike(1);
                        int count = Integer.parseInt(tvFavors.getText().toString());
                        tvFavors.setText((count - 1) + "");
                    }
                }
                break;
            case R.id.unlike:
                if (user != null) {
                    if (tvFavors != null) {
                        changeLike(1);
                        likeOrUnlike(0);
                        int count1 = Integer.parseInt(tvFavors.getText().toString());
                        tvFavors.setText((count1 + 1) + "");
                    }
                } else {
                    goLogin();
                }
                break;
            case R.id.jubao:
                if (user != null) {
                    showDialog();
                } else {
                    goLogin();
                }
                break;
            case R.id.yingxiao:
                jubaoType = 1;
                sendReport();
                break;
            case R.id.yingsui:
                jubaoType = 2;
                sendReport();
                break;
            case R.id.bushi:
                jubaoType = 3;
                sendReport();
                break;
            case R.id.mingan:
                jubaoType = 4;
                sendReport();
                break;
            case R.id.chaoxi:
                jubaoType = 5;
                sendReport();
                break;
            case R.id.saorao:
                jubaoType = 6;
                sendReport();
                break;
            case R.id.xuni:
                jubaoType = 7;
                sendReport();
                break;
            case R.id.cancel:
                if (mDialog != null) {
                    mDialog.dismiss();
                }
                break;
        }
    }

    private AlertDialog mDialog;
    private int jubaoType = 0;

    public void showDialog() {
        View v = LayoutInflater.from(this).inflate(R.layout.report_content, null);
        initDialogViewAndListener(v);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        mDialog = builder.setView(v).create();
        mDialog.show();
    }

    private void initDialogViewAndListener(View v) {
        (v.findViewById(R.id.yingxiao)).setOnClickListener(this);
        (v.findViewById(R.id.yingsui)).setOnClickListener(this);
        (v.findViewById(R.id.bushi)).setOnClickListener(this);
        (v.findViewById(R.id.mingan)).setOnClickListener(this);
        (v.findViewById(R.id.chaoxi)).setOnClickListener(this);
        (v.findViewById(R.id.saorao)).setOnClickListener(this);
        (v.findViewById(R.id.xuni)).setOnClickListener(this);
    }

    public void sendReport() {
        if (mDialog != null) {
            mDialog.dismiss();
        }
        new AlertDialog.Builder(this).setTitle("提醒").setMessage("确认举报该内容?")
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setNegativeButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Map<String, String> params = new HashMap<>();
                params.put("targetId", id + "");
                params.put("type", "1");
                params.put("descIndex", jubaoType + "");
                params.put("acc_token", UserTools.getUser(TopicDetailActivity.this).getAcc_token());
                VolleyTool.get(TopicDetailActivity.this, Constants.REPORT_URL, params, null, 0, null);
                Toast.makeText(TopicDetailActivity.this, "我们已经收到您的举报，我们会认真审查", Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        }).show();
    }

    private void goLogin() {
        Intent intent = new Intent();
        intent.setClass(this, LoginActivity.class);
        startActivity(intent);
    }

    private void goOtherAcitity(Intent intent) {
        if (user == null) {
            Intent intent1 = new Intent();
            intent1.setClass(this, LoginActivity.class);
            startActivity(intent1);
        } else {
            startActivity(intent);
        }
    }

}
